# -*- coding: utf-8 -*-
# python3编译脚本
#
import subprocess
from winotify import Notification
import time
import os
from datetime import datetime

def build_project():
    try:
        # 获取当前时间戳
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        
        # 准备初始日志内容
        log_content = f"[{timestamp}]\nStarting build process...\n"
        with open("build.log", "a", encoding="utf-8") as log_file:
            log_file.write(log_content)
        
        # 使用Popen执行cargo build命令，实时捕获输出
        process = subprocess.Popen(
            ['cargo', 'build'],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            bufsize=1,
            universal_newlines=True
        )
        
        # 实时读取并记录输出
        build_output = []
        build_error = []
        
        while True:
            output_line = process.stdout.readline()
            error_line = process.stderr.readline()
            
            if output_line:
                build_output.append(output_line)
                with open("build.log", "a", encoding="utf-8") as log_file:
                    log_file.write(f"[stdout] {output_line}")
                    
            if error_line:
                build_error.append(error_line)
                with open("build.log", "a", encoding="utf-8") as log_file:
                    log_file.write(f"[stderr] {error_line}")
                    
            # 检查进程是否结束
            if output_line == '' and error_line == '' and process.poll() is not None:
                break
        
        # 获取返回码
        return_code = process.poll()
        
        # 写入构建结果
        with open("build.log", "a", encoding="utf-8") as log_file:
            if return_code == 0:
                log_file.write("\nBuild Status: SUCCESS\n")
            else:
                log_file.write("\nBuild Status: FAILED\n")
            log_file.write("-" * 50 + "\n\n")
        
        # 创建通知对象
        toast = Notification(
            app_id="Rust Builder",
            title="Rust Build Result",
            duration="short"
        )

        if return_code == 0:
            # 编译成功
            toast.msg = "Build succeeded! ✅"
            toast.icon = os.path.abspath("./assets/success.png")
        else:
            # 编译失败
            error_msg = ''.join(build_error)
            toast.msg = f"Build failed! ❌\n{error_msg}"
            toast.icon = os.path.abspath("./assets/error.png")

        # 显示通知
        toast.show()

    except Exception as e:
        # 获取当前时间戳
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        
        # 记录异常到日志
        error_log = f"[{timestamp}]\nBuild Status: ERROR\nError Message: {str(e)}\n{'-' * 50}\n\n"
        with open("build.log", "a", encoding="utf-8") as log_file:
            log_file.write(error_log)
            
        # 处理异常情况
        toast = Notification(
            app_id="Rust Builder",
            title="Build Error",
            msg=f"Error occurred: {str(e)}",
            duration="short"
        )
        toast.show()

if __name__ == "__main__":
    build_project()